﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using System.Drawing.Imaging;

namespace _114sct
{
    /// <summary>
    /// upload 的摘要说明
    /// </summary>
    public class upload : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            context.Response.Expires = -1;
            try
            {
                HttpPostedFile fileData = context.Request.Files["Filedata"];
                string oldcredentials = context.Request.Params["credentials"];
                string brandname = context.Request.Params["brandname"];
                if (FileIsWebFriendlyImage(fileData.InputStream) == false) context.Response.Write("Invaild file type");
                if (string.IsNullOrEmpty(oldcredentials) == false)
                {
                    try
                    {
                        System.IO.File.Delete(context.Server.MapPath("~/uploads/" + oldcredentials));
                    }
                    catch
                    {
                        context.Response.Write("Retry");
                    }
                }
                Guid newid = Guid.NewGuid();
                string ext = System.IO.Path.GetExtension(fileData.FileName);
                string fileName = context.Server.MapPath("~/uploads/" + brandname + newid.ToString("N") + ext);
                fileData.SaveAs(fileName);

                context.Response.Write("ok|" + brandname + newid.ToString("N") + ext);
                context.Response.StatusCode = 200;
            }
            catch (Exception ex)
            {
                context.Response.Write("Error: " + ex.Message);
            }
        }
        private bool FileIsWebFriendlyImage(Stream stream)
        {
            try
            {
                //Read an image from the stream...
                var i = System.Drawing.Image.FromStream(stream);

                //Move the pointer back to the beginning of the stream
                stream.Seek(0, SeekOrigin.Begin);

                if (ImageFormat.Jpeg.Equals(i.RawFormat))
                    return true;
                return ImageFormat.Png.Equals(i.RawFormat) || ImageFormat.Gif.Equals(i.RawFormat);
            }
            catch
            {
                return false;
            }
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}